﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PlatformUW.Contracts;
using PlatformUW.Entities.DataShaping;
using PlatformUW.Entities.Dtos;
using PlatformUW.Entities.RequestFeatures;

namespace PlatformUW.API.Controllers
{
    [Route("api/sensor")]
    [ApiController]
    public class SensorController : ControllerBase
    {
        private readonly IRepositoryWrapper repositoryWrapper;
        private readonly ILogger<PlayerController> logger;
        private readonly IMapper mapper;

        public SensorController(IRepositoryWrapper repositoryWrapper,
            ILogger<PlayerController> logger,
            IMapper mapper)
        {
            this.repositoryWrapper = repositoryWrapper;
            this.logger = logger;
            this.mapper = mapper;
        }

        [HttpGet("all")]
        public async Task<IActionResult> GetAllSensors([FromQuery] SensorParameter parameter)
        {
            try
            {
                if (!parameter.ValidateDateRange())
                {
                    return BadRequest("Invalid date range.");
                }

                var sensors = await repositoryWrapper.Sensor.GetAllSensorsAsync(parameter);
                Response.Headers.Append("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(sensors.MetaData));
                var result = mapper.Map<IEnumerable<SensorDto>>(sensors).ShapeData(parameter.Fields);
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "Alarm");
                return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
            }
        }

    }
}
